package com.alpha.service.config;

import com.alpha.core.http.AlphaHttpContext;
import com.alpha.core.http.HttpConstants;
import com.alpha.core.utils.JsonUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * mvc 配置
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@ConditionalOnClass({WebMvcConfigurer.class})
@Configuration
public class AlphaWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(@Nonnull HttpServletRequest request,
                                     @Nonnull HttpServletResponse response,
                                     @Nonnull Object handler) {
                AlphaHttpContext.setContext(JsonUtil.toMap(request.getHeader(HttpConstants.CLAIMS)));
                return true;
            }

            @Override
            public void afterCompletion(@Nonnull HttpServletRequest request,
                                        @Nonnull HttpServletResponse response,
                                        @Nonnull Object handler, Exception ex) {
                AlphaHttpContext.clear();
            }
        });
    }
}
